package com.tongji.diy.view.component3D
{
	import com.tongji.diy.event.UploadRoomVertexEvent;
	import com.tongji.diy.utils.RoomParameters;
	
	import de.polygonal.ds.DListNode;
	
	import flare.basic.Scene3D;
	import flare.core.Mesh3D;
	import flare.core.Surface3D;
	import flare.events.MouseEvent3D;
	import flare.materials.Material3D;
	
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Vector3D;
	
	/**
	 * 
	 * @author xxj
	 * 
	 */
	
	public class RoomVertex extends Mesh3D
	{
		protected var material:Material3D;
		public var node:DListNode;
		public var lock:Boolean;
		
		protected const RANGE:uint = 2;
		protected const DIFF:uint = 1;
		
		public function RoomVertex(node:DListNode, material:Material3D)
		{
			this.node = node;
			node.data.vertex = this;
			this.material = material;
			surfaces[0] = new Surface3D();
			surfaces[0].material = material;
			surfaces[0].addVertexData( Surface3D.POSITION );
			surfaces[0].addVertexData( Surface3D.UV0 );
			surfaces[0].addVertexData( Surface3D.NORMAL );
			
			var radius:Number = RoomParameters.wallWidth/2;
			var part:uint = 16;
			surfaces[0].vertexVector.push(0, 0, 0, 0, 0, 0, 0, 1);
			for (var i:uint = 0; i<part; i++)
			{
				surfaces[0].vertexVector.push(radius*Math.cos(2*Math.PI*i/part), 0, -radius*Math.sin(2*Math.PI*i/part), 0, 1, 0, 0, 1);
			}
			
			for (i = 1; i<=part; i++)
			{
				if (i != part)
					surfaces[0].indexVector.push(0,i,i+1);
				else
					surfaces[0].indexVector.push(0,i,1);
			}
			
			this.x = node.data.x;
			this.y = RoomParameters.wallHeight + 1;
			this.z = node.data.y;
		}
		
		public function refresh():void
		{
			this.x = node.data.x;
			this.z = node.data.y;
		}
		
		//Scene3D.RENDER_EVENT
		public function renderHandler():void
		{
			var vec:Vector3D = this.getPosition(false);
			var point:Point = new Point(vec.x,vec.z);
			
			var abs:Number = Math.abs(point.x);
			var tmp:int = int(abs);
			if( (tmp+this.DIFF) % this.RANGE <= 2 * this.DIFF )
			{
				//51%10<2
				if(tmp%this.RANGE<=this.DIFF)
				{
					abs = int(tmp/this.RANGE)*this.RANGE;
				}
				else
				{
					abs = (int(tmp/this.RANGE)+1)*this.RANGE;
				}
				
				if(point.x<0)
					point.x = -abs;
				else
					point.x = abs;
			}
			
			abs = Math.abs(point.y);
			tmp = int(abs);
			if( (tmp+this.DIFF) % this.RANGE <= 2 * this.DIFF )
			{
				//51%10<2
				if(tmp%this.RANGE<=this.DIFF)
				{
					abs = int(tmp/this.RANGE)*this.RANGE;
				}
				else
				{
					abs = (int(tmp/this.RANGE)+1)*this.RANGE;
				}
				
				if(point.y<0)
					point.y = -abs;
				else
					point.y = abs;
			}
			point = this.node.data.parentRoom.globalToLocal(point);
			this.scene.dispatchEvent(new UploadRoomVertexEvent( UploadRoomVertexEvent.UPLOAD_ROOM_VERTEX, this, point));
		}
		
	}
}